package com.reggie.background.common;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 短信发送工具类
 */
public class SMSUtils {
	private static String accessKeyId;
	private static String accessKeySecret;
	private static String signName;
	private static String templateCode;
	private static Client  client;
	static {
		Yaml yaml = new Yaml();
		InputStream in=SMSUtils.class.getClassLoader().getResourceAsStream("application.yml");
		Map  load = yaml.load(in);
		SMSUtils.accessKeyId= (String) load.get("accessKeyId");
		SMSUtils.accessKeySecret= (String) load.get("accessKeySecret");
		SMSUtils.signName= (String) load.get("signName");
		SMSUtils.templateCode= (String) load.get("templateCode");
		Config config = new Config()
				// 您的 AccessKey ID
				.setAccessKeyId(SMSUtils.accessKeyId)
				// 您的 AccessKey Secret
				.setAccessKeySecret(SMSUtils.accessKeySecret);
		// 访问的域名
		config.endpoint = "dysmsapi.aliyuncs.com";
		try {
			SMSUtils.client=new Client(config);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}



	public static boolean sendMessage(String phoneNumbers,String param){
		SendSmsRequest sendSmsRequest = new SendSmsRequest()
				.setSignName(SMSUtils.signName)
				.setTemplateCode(SMSUtils.templateCode)
				.setPhoneNumbers(phoneNumbers)
				.setTemplateParam("{\"code\":\""+param+"\"}");
		RuntimeOptions runtime = new RuntimeOptions();
		try {
			SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
			System.out.println("短信发送返回："+sendSmsResponse.getBody().getMessage());
			if (sendSmsResponse.getBody().getMessage().contains("OK")){
				return true;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return false;

	}


	public static void main(String[] args) {
		Integer integer = ValidateCodeUtils.generateValidateCode(6);

		SMSUtils.sendMessage("15360578912",Integer.toString(integer));
	}

}
